<template>
  <div class="app-container app-container-next app-container-detail time-limit" ref="container">
    <el-card class="box-card site" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'time-limit-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <div class="steps">
        <el-steps :active="activeForm" align-center>
          <el-step title="创建活动"></el-step>
          <el-step title="活动页面设置"></el-step>
        </el-steps>
      </div>
      <el-row style="margin-top: 20px" v-if="activeForm === 1">
        <el-col :span="24">
          <el-form ref="rebateForm" :model="timeLimit" :rules="rules" label-width="120px">
            <h4 class="rebate-label">基本信息</h4>
            <el-form-item label="名称：" prop="name">
              <el-input v-model="timeLimit.name" placeholder="请输入活动名称" style="width: 460px" maxlength="20"/>
            </el-form-item>
            <el-form-item label="活动时间：" prop="date" style="margin-top: 15px">
              <al-date-picker v-model="timeLimit.date" format="yyyy-MM-dd HH:mm:ss" size="small"></al-date-picker>
            </el-form-item>
            <h4 class="rebate-label">使用规则</h4>
            <el-form-item label="限购规则：" prop="useRule" class="no-border">
              <el-radio-group v-model="timeLimit.useRule" class="radio-item-group">
                <el-radio label="none">无限制</el-radio>
                <el-radio label="number_limit" class="radio-item">
                  每单限购
                  <el-form-item v-if="timeLimit.useRule === 'number_limit'" class="item" prop="limitCount">
                    <el-input v-model="timeLimit.limitCount" placeholder="请输入" class="radio-item-input" type="number"
                              @input="handleLimitNumInput" style="width: 180px;"
                              onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}">
                      <template slot="append">
                        件
                      </template>
                    </el-input>
                    <span style="color: black">(超出后全部按售价)</span>
                  </el-form-item>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <h4 class="rebate-label">优惠规则</h4>
            <el-form-item label="促销类型：" prop="promotionType" class="no-border">
              <el-radio-group v-model="timeLimit.discountRule">
                <el-radio label="fixed_discount">固定折扣</el-radio>
                <el-radio label="fixed_price">固定减价</el-radio>
              </el-radio-group>
            </el-form-item>
            <h4 class="rebate-label">使用范围
              <el-button type="primary" @click="handleSelectProduct">选择商品
              </el-button
              >
              <span style="font-weight: normal;margin-left: 12px;font-size: 14px"
                    v-if="timeLimit.mmsTimeLimitProductList.length!==0">已选择{{
                  timeLimit.mmsTimeLimitProductList.length
                }}件商品</span>
            </h4>
            <el-form-item label="商品排序展示：" class="no-border">
              <el-select v-model="timeLimit.sort" placeholder="请选择" style="width: 200px">
                <el-option label="价格从低到高" value="price_low_to_high"/>
                <el-option label="价格从高到低" value="price_high_to_low"/>
                <el-option label="实际销量从高到低" value="sale_count_high_to_low"/>
                <el-option label="虚拟销量从高到低" value="virtual_sale_count_high_to_low"/>
              </el-select>
            </el-form-item>
            批量设置
            <el-table :data="timeLimit.batchSettings" fit highlight-current-row
                      v-if="timeLimit.mmsTimeLimitProductList.length">
              <el-table-column align="center" label="商品图片">
                <template>
                  商品图片
                </template>
              </el-table-column>
              <el-table-column align="center" label="商品名称" prop="productName">
                <template>
                  --
                </template>
              </el-table-column>
              <el-table-column align="center" label="款式" prop="productSpec">
                <template>
                  --
                </template>
              </el-table-column>
              <el-table-column align="center" :label="'售价/虚拟价(' + currencyType + ')'">
                <template>
                  --
                </template>
              </el-table-column>
              <el-table-column align="center" label="折扣/减价" width="250">
                <template slot-scope="scope">
                  <el-form-item :prop="'batchSettings.' + scope.$index + '.allDiscount'"
                                :rules="[{validator: validateDiscount, trigger: 'blur'}]">
                    <el-input style="width: 180px" v-model="scope.row.allDiscount"
                              @input="handleAllDiscount(scope.row.allDiscount)"
                              @blur="handleAllDiscountRulesChange('rebateForm')"
                              onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))">
                      <template slot="append">{{ timeLimit.discountRule === 'fixed_discount' ? '%' : currencyType }}</template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" :label="'促销价(' + currencyType + ')'">
                <template>
                  --
                </template>
              </el-table-column>
              <el-table-column align="center" label="售卖上限" prop="limitCount">
                <template slot-scope="scope">
                  <el-form-item :prop="'batchSettings.' + scope.$index + '.allLimitCount'">
                    <el-input v-model="scope.row.allLimitCount" @input="handleLimitCount(scope.row.allLimitCount)"
                              onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="已售" prop="hasSale">
                <template>
                  --
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template>
                  --
                </template>
              </el-table-column>
            </el-table>
            <el-table :data="timeLimit.mmsTimeLimitProductList" fit highlight-current-row
                      :class="{'hidden-table-header': timeLimit.mmsTimeLimitProductList.length > 0}">
              <el-table-column align="center" label="商品图片">
                <template slot-scope="scope">
                  <el-image
                      slot="reference"
                      style="width: 80px; height: 60px;cursor: pointer;"
                      :src="scope.row.productImage"
                      fit="contain"></el-image>
                </template>
              </el-table-column>
              <el-table-column align="center" label="商品名称" prop="productName" :show-overflow-tooltip="true"/>
              <el-table-column align="center" label="款式" prop="productSpec" :show-overflow-tooltip="true"/>
              <el-table-column align="center" :label="'售价/虚拟价(' + currencyType + ')'" prop="salePrice/virtualSellPrice">
                <template slot-scope="{row}">
                  <p>{{ row.sellPrice|currency('$') }}</p>
                  <p>
                    <del>{{ row.virtualSellPrice|currency('$') }}</del>
                  </p>
                </template>
              </el-table-column>
              <el-table-column align="center" label="折扣/减价" prop="discount" width="250">
                <template slot-scope="scope">
                  <el-form-item :prop="'mmsTimeLimitProductList.' + scope.$index + '.discount'"
                                :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}, {validator: validateDiscount, trigger: 'blur'}]">
                    <el-input style="width: 180px" v-model.number="scope.row.discount"
                              @input="singleCalculation(scope.row, timeLimit.discountRule)"
                              onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))">
                      <template slot="append">{{ timeLimit.discountRule === 'fixed_discount' ? '%' : currencyType }}</template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" :label="'促销价(' + currencyType + ')'" prop="showSalePrice"/>
              <el-table-column align="center" label="售卖上限" prop="limitCount">
                <template slot-scope="scope">
                  <el-form-item :prop="'mmsTimeLimitProductList.' + scope.$index + '.limitCount'">
                    <el-input v-model.number="scope.row.limitCount"
                              onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="已售" prop="hasSale"></el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" plain type="danger" @click="handleRemove(scope.$index, scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item class="fixBottom">
              <el-button type="primary" @click="nextStep('rebateForm')">下一步</el-button>
              <el-button @click="handleReset">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px" v-if="activeForm === 2">
        <el-col :span="18">
          <el-form ref="rebateForm" :model="timeLimit2" :rules="rules" label-width="140px">
            <h4 style="margin-bottom: 20px">活动Banner <span class="desc">推荐尺寸：
                <span v-if="timeLimit2.displayMode==='full'">1920PX * 300PX</span>
                <span v-if="timeLimit2.displayMode!=='full'">1410PX * 300PX</span>
              </span>
            </h4>
            <el-form-item>
              <upload-file accept="image/jpeg,image/jpg,image/png"
                           :fileType="['png', 'jpg', 'jpeg']"
                           :isShowTip="true"
                           :lazy="true"
                           :responseFn="handleResponse"
                           :action="uploadPath"
                           title="图片"
                           v-model="timeLimit2.imageUrl"
              ></upload-file>
            </el-form-item>
            <el-form-item label="展示方式">
              <el-radio-group v-model="timeLimit2.displayMode">
                <el-radio label="full">铺满全屏</el-radio>
                <el-radio label="padding">两边留白</el-radio>
              </el-radio-group>
            </el-form-item>
            <h4>倒计时提醒文案 <span class="desc">该提醒文案将展示在活动页面 banner 下方</span><span class="desc text-blue"
                                                                               @click="handleResetColor">重置配色</span>
            </h4>
            <div class="preview"
                 :style="{background: `linear-gradient(90deg, ${timeLimit2.countdown.baseMap1}, ${timeLimit2.countdown.baseMap2})`}"
                 style="margin-bottom:20px;">
              <div><span class="flashsale_text" :style="{color: timeLimit2.countdown.copyColor}">FLASH SALE</span><span
                  style="margin-left: 12px; color: rgb(254, 255, 254);"><span class="inline-block"
                                                                              style="margin-right: 10px;">End in </span></span>
                <span v-if="timeLimit2.unit === '1'"><span class="time"
                                                           :style="{color: timeLimit2.countdown.countdownCopyColor, background: timeLimit2.countdown.backgroundColor}">73</span><span
                    style="margin: 0px 4px;color: #fff">Day</span></span>
                <span class="time"
                      :style="{color: timeLimit2.countdown.countdownCopyColor, background: timeLimit2.countdown.backgroundColor}">16</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="time"
                                                                       :style="{color: timeLimit2.countdown.countdownCopyColor, background: timeLimit2.countdown.backgroundColor}">2</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="time"
                                                                       :style="{color: timeLimit2.countdown.countdownCopyColor, background: timeLimit2.countdown.backgroundColor}">5</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="align-bottom time"
                                                                       :style="{color: timeLimit2.countdown.countdownCopyColor, background: timeLimit2.countdown.backgroundColor}"
                                                                       style="font-size: 20px;">18</span>
              </div>
              <div class="rules_list"></div>
            </div>
            <el-form-item label="活动倒计时显示单位">
              <el-radio-group v-model="timeLimit2.unit">
                <el-radio label="1">天-时-分-秒-毫秒</el-radio>
                <el-radio label="2">时-分-秒-毫秒</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="底色">
              <el-color-picker
                  v-model="timeLimit2.countdown.baseMap1"
                  :predefine="predefineColors">
              </el-color-picker>
              <el-color-picker
                  v-model="timeLimit2.countdown.baseMap2"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="文案颜色">
              <el-color-picker
                  v-model="timeLimit2.countdown.copyColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="倒计时背景颜色">
              <el-color-picker
                  v-model="timeLimit2.countdown.backgroundColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="倒计时文案颜色">
              <el-color-picker
                  v-model="timeLimit2.countdown.countdownCopyColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <h4>商品详情展示信息 <span class="desc">选择商品详情页将展示的活动信息</span></h4>
            <el-form-item label="">
              <el-checkbox-group v-model="timeLimit2.countdown.detailsDisplay">
                <el-checkbox label="1">活动倒计时</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <h4>颜色配置 <span class="desc">配置商品详情页的限时促销信息样式</span><span class="desc text-blue"
                                                                     @click="handleResetDetailColor">重置配色</span></h4>
            <div style="display: flex;height: 300px;overflow: hidden">
              <div style="margin-top: 20px">
                <el-form-item label="活动背景颜色">
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.baseMap1"
                      :predefine="predefineColors">
                  </el-color-picker>
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.baseMap2"
                      :predefine="predefineColors">
                  </el-color-picker>
                </el-form-item>
                <el-form-item label="文字背景颜色">
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.textBackground"
                      :predefine="predefineColors">
                  </el-color-picker>
                </el-form-item>
                <el-form-item label="Flash sale文字颜色">
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.flashSaleColor"
                      :predefine="predefineColors">
                  </el-color-picker>
                </el-form-item>
                <el-form-item label="文字颜色">
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.textColor"
                      :predefine="predefineColors">
                  </el-color-picker>
                  <el-color-picker
                      v-model="timeLimit2.colorScheme.textColor2"
                      :predefine="predefineColors">
                  </el-color-picker>
                </el-form-item>
              </div>
              <div class="preview_wrap">
                <div class="change_wrap"
                     :style="{background: `linear-gradient(90deg, ${timeLimit2.colorScheme.baseMap1}, ${timeLimit2.colorScheme.baseMap2})`}">
                  <div class="logo"
                       :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">
                    <div class="logo_before" :style="{background: timeLimit2.colorScheme.textBackground}"></div>
                    <div class="logo_after" :style="{background: timeLimit2.colorScheme.textBackground}"></div>
                    <span class="text" :style="{color: timeLimit2.colorScheme.flashSaleColor}">Flash<br>Sale</span></div>
                  <div class="discount_info">
                    <div class="times" style="display: flex;"><span class="time_text"
                                                                    :style="{color: timeLimit2.colorScheme.textColor2}">End in</span><span
                        class="time" :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">12</span><span
                        class="time_text" :style="{color: timeLimit2.colorScheme.textColor2}">Day</span><span
                        class="time"
                        :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">23</span>
                      <span
                          class="time_text" :style="{color: timeLimit2.colorScheme.textColor2}">:</span><span
                          class="time"
                          :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">59</span><span
                          class="time_text" :style="{color: timeLimit2.colorScheme.textColor2}">:</span><span
                          class="time"
                          :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">59</span><span
                          class="time_text" :style="{color: timeLimit2.colorScheme.textColor2}">.</span><span
                          class="time ms"
                          :style="{color: timeLimit2.colorScheme.textColor, background: timeLimit2.colorScheme.textBackground}">289</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-form-item class="fixBottom">
              <el-button type="primary" @click="lastStep">上一步</el-button>
              <el-button type="primary" @click="addTimeLimit">保存</el-button>
              <el-button @click="handleReset">取消</el-button>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
    </el-card>
    <el-dialog title="选择商品" :visible.sync="productDialogVisible" width="1000px">
      <div class="search-list">
        <el-form ref="form" class="search-table-form" :model="formParams" label-width="90px" size="small"
                 style="background: #fff;padding: 10px">
          <el-row :gutter="12" style="margin: 0">
            <el-col :span="6">
              <el-form-item label="产品系列：">
                <el-select v-model="formParams.seriesId" @change="handleSearch">
                  <el-option v-for="series in seriesList" :value="series.value" :key="series.value"
                             :label="series.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品类型：">
                <el-select v-model="formParams.spuType" @change="handleSearch">
                  <el-option value="" label="全部商品"></el-option>
                  <el-option value="0" label="普通商品"></el-option>
                  <el-option value="1" label="定制商品"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上架状态：">
                <el-select v-model="formParams.published" @change="handleSearch">
                  <el-option value="" label="全部"></el-option>
                  <el-option :value="1" label="上架"></el-option>
                  <el-option :value="0" label="下架"></el-option>
                  <el-option :value="-1" label="未上架"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品名称：">
                <el-input v-model="formParams.text" placeholder="请输入" @keyup.enter.native="handleSearch" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" style="text-align: left">
              <p>
                已选择 {{ filterSelectData(productList).length }} 件商品
              </p>
            </el-col>
            <el-col :span="19" style="text-align: right">
              <el-form-item>
                <el-button size="small" type="primary" @click="handleSearch">搜索查询</el-button>
                <el-button size="small" type="default" @click="handleRest">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <tree-table
          v-loading.lock="tableLoading"
          height="600px"
          tree-props="skuDTOList"
          id-key="skuId"
          :columns="columns"
          @select="onSelect"
          @trigger="onTrigger"
          :data="tableData"
          border
          ref="treeTable"
      >
        <template slot-scope="scope" slot="product">
          <el-image :src="scope.row.productImage" style="width: 40px;height: 40px;flex: none" fit="contain"></el-image>
          <span>{{ scope.row.productName }}</span>
        </template>
      </tree-table>
      <LoadMore  :loading="tableLoading" v-if="tableData.length > 0 && !isMore" :is-more="isMore" @on-change="onLoad"></LoadMore>
      <span slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProductList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uploadFile from '_c/Upload/uploadFile';
import {addTimeLimit, getTimeLimitSpuPage} from '@/api/time-limit';
import {getSeriesList} from '@/api/goods';
import TreeTable from '_c/Tables/tree-table';
import {debounce, subPrice, divisionPrice, deepClone} from '@/utils/utils';
import {currency} from '@/utils/filters';
import LoadMore from '@/components/LoadMore';
import {mapGetters} from 'vuex';

export default {
    name: 'time-limit-add',
    components: {uploadFile, TreeTable, LoadMore},
    data () {
        return {
            isMore: false,
            tableLoading: false,
            formParams: {
                page: 1,
                pageSize: 25,
                spuType: '',
                text: '',
                seriesId: '',
                published: ''
            },
            seriesList: [],
            tableData: [],
            predefineColors: [
                '#ff4500',
                '#ff8c00',
                '#ffd700',
                '#90ee90',
                '#00ced1',
                '#1e90ff',
                '#c71585',
                'rgba(255, 69, 0, 0.68)',
                'rgb(255, 120, 0)',
                'hsv(51, 100, 98)',
                'hsva(120, 40, 94, 0.5)',
                'hsl(181, 100%, 37%)',
                'hsla(209, 100%, 56%, 0.73)'
            ],
            columns: [
                {
                    label: '',
                    type: 'selection',
                    selectable (row, index) {
                        if (row.disable) {
                            return 0;
                        } else {
                            return 1;
                        }
                    }
                },
                {
                    label: '商品',
                    prop: 'productName',
                    showOverflowTooltip: true,
                    slotName: 'product',
                    align: 'center',
                    width: '300px'
                },
                {
                    label: '款式',
                    prop: 'skuValues',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '价格',
                    render: row => {
                        return currency(row.sellPrice, '$', 2);
                    },
                    align: 'center'
                },
                {
                    label: '备注',
                    prop: 'description',
                    align: 'center'
                }
            ],
            productDialogVisible: false,
            timeLimit: {
                siteId: this.siteId,
                name: '',
                date: [],
                beginDate: '',
                endDate: '',
                useRule: 'none',
                limitCount: '',
                discountRule: 'fixed_discount',
                sort: 'price_low_to_high',
                batchSettings: [{}],
                mmsTimeLimitProductList: [],
                styleJson: {}

            },
            productList: [],
            timeLimit2: {
                imageUrl: '',
                displayMode: 'full',
                unit: '1',
                countdown: {
                    detailsDisplay: ['1', '2'],
                    baseMap1: 'rgb(255, 72, 72)',
                    baseMap2: 'rgb(255, 13, 125)',
                    copyColor: 'rgb(254, 255, 254)',
                    backgroundColor: 'rgb(255, 243, 203)',
                    countdownCopyColor: 'rgb(0, 0, 0)'
                },
                colorScheme: {
                    baseMap1: 'rgb(255, 72, 72)',
                    baseMap2: 'rgb(255, 13, 125)',
                    textBackground: 'rgb(255, 243, 203)',
                    flashSaleColor: 'rgb(231, 6, 73)',
                    textColor: 'rgb(0, 0, 0)',
                    textColor2: 'rgb(255, 255, 255)'

                }
            },
            uploadPath: process.env.VUE_APP_BASE_API + '/upload-file',
            activeForm: 1,
            rules: {
                name: [
                    {required: true, message: '请输入活动名称', trigger: 'blur'}
                ],
                date: [
                    {required: true, message: '请选择开始时间', trigger: 'blur'}
                ],
                limitCount: [
                    {required: true, message: '请输入', trigger: 'blur'}
                ],
                ruleCondition: [
                    {required: true, message: '请设置条件逻辑', trigger: 'blur'}
                ]
            },
            validateDiscount: (rule, value, callback) => {
                const index = rule.field.split('.')[1];
                let one = Number(value);
                if (this.timeLimit.discountRule === 'fixed_discount') {
                    if (one > 99) {
                        return callback(new Error('折扣不能超过99'));
                    }
                } else {
                    if (this.timeLimit.mmsTimeLimitProductList[index].virtualSellPrice < one * 100) {
                        return callback(new Error('减价不能超过虚拟价'));
                    }
                }
                return callback();
            },
            submitLoading: false,
            total: 0
        };
    },
    watch: {
        'timeLimit.date' (newValue, oldValue) {
            if (newValue) {
                this.timeLimit.mmsTimeLimitProductList = [];
                this.productList = [];
                if (this.$refs.treeTable) {
                    this.$refs.treeTable.setSelected(this.timeLimit.mmsTimeLimitProductList);
                }
            }
        },
        activeForm (newValue, oldValue) {
            if (newValue) {
                this.$nextTick(() => {
                    this.$refs.container.scrollTo(0, 0);
                });
            }
        }
    },
    methods: {
        onLoad () {
            this.formParams.page++;
            this.getData().then(() => {
                this.$refs.treeTable.setSelected(this.timeLimit.mmsTimeLimitProductList);
            });
        },
        getData (params = {}) {
            params.siteId = this.siteId;
            params.beginDate = new Date(this.timestampToTime(this.timeLimit.date[0]) + ' UTC' + this.timeZone).getTime();
            params.endDate = new Date(this.timestampToTime(this.timeLimit.date[1]) + ' UTC' + this.timeZone).getTime();
            console.info(params);
            this.tableLoading = true;
            return new Promise(resolve => {
                getTimeLimitSpuPage({...params, ...this.formParams}).then(res => {
                    this.total = res.totalElements;
                    this.tableLoading = false;
                    if (res.records.length === 0) {
                        // 加载结束
                        this.isMore = true;
                    }
                    if (res.records.length < this.formParams.pageSize) {
                        this.isMore = true;
                    }
                    if (this.formParams.page === 1) {
                        this.tableData = res.records;
                    } else {
                        this.tableData = this.tableData.concat(res.records);
                    }
                    resolve();
                });
            });
        },
        getSeriesList () {
            getSeriesList({siteId: this.siteId}).then(res => {
                if (res.data !== undefined && res.data.length > 0) {
                    const seriesList = [];
                    seriesList.push({value: '', label: '全部'});
                    for (const object of res.data) {
                        seriesList.push({value: object.value, label: object.label});
                    }
                    this.seriesList = seriesList;
                }
            });
        },
        handleSearch () {
            this.formParams.page = 1;
            this.getData();
        },
        handleRest () {
            this.formParams = {
                page: 1,
                pageSize: 50,
                text: '',
                seriesId: '',
                published: ''
            };
            this.getData();
        },
        handleResponse (response, file, fileList) {
            return response;
        },
        nextStep (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    if (!this.timeLimit.mmsTimeLimitProductList.length) {
                        this.$message.error('请先选择商品');
                    } else {
                        this.activeForm = 2;
                    }
                }
            });
        },
        lastStep () {
            this.activeForm -= 1;
        },
        handleReset () {
            this.$router.push({name: 'time-limit-list'});
        },
        handleSelectProduct () {
            if (this.timeLimit.date.length === 2) {
                this.productDialogVisible = true;
                if (!this.productList.length) {
                    this.getData();
                }
            } else {
                this.$message.error('请选择活动时间');
            }
        },
        onSelect: debounce(function (selection) {
            if (selection.length > 400) {
            // this.$refs.treeTable.clearSelection();
                this.$message.error('建议不超过400个sku， 页面会出现卡顿');
            }
            this.productList = selection;
        }, 600),
        onTrigger (row, expanded) {
            row.$expanded = expanded;
        },
        filterSelectData (data) {
            return data.filter(item => item.$level === 1);
        },
        saveProductList () {
            this.productDialogVisible = false;
            this.productList.forEach((res) => {
                if (!res.discount) {
                    res.discount = null;
                }
                if (!res.limitCount) {
                    res.limitCount = null;
                }
            });
            this.timeLimit.mmsTimeLimitProductList = this.filterSelectData(deepClone(this.productList));
        },

        // 单行计算
        singleCalculation (item, type) {
            if (type === 'fixed_discount') {
                item.salePrice = item.virtualSellPrice * (100 - item.discount) / 100;
                item.showSalePrice = currency(item.virtualSellPrice * (100 - item.discount) / 100, '$', 2);
            } else {
                item.salePrice = subPrice(item.virtualSellPrice, item.discount * 100);
                item.showSalePrice = currency(subPrice(item.virtualSellPrice, item.discount * 100), '$', 2);
            }
        },
        // 当行删除
        handleRemove (index, item) {
            this.timeLimit.mmsTimeLimitProductList.splice(index, 1);
            const parentIndex = this.productList.findIndex((v) => v.skuId === item.$parent);
            this.productList.splice(parentIndex, 1);
            const delIndex = this.productList.findIndex((v) => item.$parent === v.$parent);
            this.productList.splice(delIndex, 1);
            this.$refs.treeTable.setSelected(this.productList);
        },
        // 批量计算
        handleAllDiscount (val) {
            this.timeLimit.mmsTimeLimitProductList.forEach((res) => {
                res.discount = val;
                this.singleCalculation(res, this.timeLimit.discountRule);
            });
        },
        handleLimitCount (val) {
            this.timeLimit.mmsTimeLimitProductList.forEach((res) => {
                res.limitCount = val;
            });
        },
        addTimeLimit () {
            this.timeLimit.beginDate = new Date(this.timestampToTime(this.timeLimit.date[0]) + ' UTC' + this.timeZone).getTime();
            this.timeLimit.endDate = new Date(this.timestampToTime(this.timeLimit.date[1]) + ' UTC' + this.timeZone).getTime();
            this.timeLimit.siteId = this.siteId;
            // if (this.timeLimit2.imageUrl === null) {
            //     this.$message.warning('请等待图片上传成功');
            //     return;
            // }
            this.timeLimit.styleJson = JSON.stringify(this.timeLimit2);
            console.info(this.timeLimit);
            this.submitLoading = true;
            addTimeLimit(this.timeLimit).then(res => {
                if (res.code === '200') {
                    this.submitLoading = false;
                    this.$message.success('新增成功');
                    this.handleReset('time-limit-list');
                }
            }).catch(() => {
                this.submitLoading = false;
            });
        },
        timestampToTime (timestamp) {
            var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            let strDate = Y + M + D + h + m + s;
            return strDate;
        },
        handleLimitNumInput () {
            if (this.timeLimit.limitCount.length === 1) {
                this.timeLimit.limitCount = this.timeLimit.limitCount.replace(/[^1-9]/g, '');
            } else {
                this.timeLimit.limitCount = this.timeLimit.limitCount.replace(/\D/g, '');
            }
        },
        handleResetColor () {
            this.timeLimit2.countdown = {
                detailsDisplay: ['1', '2'],
                baseMap1: 'rgb(255, 72, 72)',
                baseMap2: 'rgb(255, 13, 125)',
                copyColor: 'rgb(254, 255, 254)',
                backgroundColor: 'rgb(255, 243, 203)',
                countdownCopyColor: 'rgb(0, 0, 0)'
            };
        },
        handleResetDetailColor () {
            this.timeLimit2.colorScheme = {
                baseMap1: 'rgb(255, 72, 72)',
                baseMap2: 'rgb(255, 13, 125)',
                textBackground: 'rgb(255, 243, 203)',
                flashSaleColor: 'rgb(231, 6, 73)',
                textColor: 'rgb(0, 0, 0)',
                textColor2: 'rgb(255, 255, 255)'
            };
        },
        handleAllDiscountRulesChange (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    if (!this.timeLimit.mmsTimeLimitProductList.length) {
                        this.$message.error('请先选择商品');
                    }
                }
            });
        }
    },
    computed: {
        ...mapGetters(['timeZone', 'siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencyType () {
            return this.siteInfo.currencyType;
        }
    },
    created () {
        this.getSeriesList();
    }
};
</script>

<style scoped lang="scss">
.app-container {
  overflow: scroll;
  height: 800px;
}
.steps {
  width: 40%;
  margin: 10px auto;
}

.rebate-label {
  margin-bottom: 20px !important;
}

.radio-item-group {
  display: flex;
  align-items: center;
  height: 40px;

  .radio-item {
    display: flex;
    align-items: center;

    .radio-item-input {
      margin-left: 10px;
    }
  }
}

.groups-conditions {
  display: flex;
  align-items: center;

  .item {
    margin-right: 20px;
    margin-bottom: 20px;
  }
}

.preview {
  margin: 20px 0 0 0;
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #ff4848, #ff0d7d);
  padding: 0 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;

  .flashsale_text {
    font-size: 16px;
    font-weight: 700;
  }

  .inline-block {
    display: inline-block;
  }

  .time {
    display: inline-block;
    padding: 0 4px;
    min-width: 35px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 4px;
  }
}

.sorting-panel {
  .search {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .inline-item {
      width: 200px;
    }
  }

  .list-wrap {
    > div {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .image-item {
      position: relative;
      margin-right: 10px;
      margin-bottom: 10px;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      width: 200px;
      background-color: #f7f7f7;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 10px;

      .img {
        position: relative;
        height: 148px;

        img {
          width: 148px;
          height: 148px;
        }

        &:hover {
          .label {
            display: flex;
          }
        }
      }

      .title {
        height: 36px;
        margin: 5px 0;
        color: #30344f;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: center;
        width: 100%;
      }

      .label {
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 32px;
        text-align: center;
        position: absolute;
        bottom: 0;
        background-color: #000000;
        color: white;
        opacity: 0.6;
        display: none;
        line-height: 32px;
      }
    }
  }
}

.text-blue {
  color: #409EFF !important;
  text-decoration: underline;
  cursor: pointer;
}
</style>

<style lang="scss">
.radio-item-group {
  display: flex;
  align-items: center;

  .radio-item {
    display: flex;
    align-items: center;

    .el-radio__label {
      display: flex;
      align-items: center;
    }
  }
}

.time-limit {
  .el-form-item__content {
    line-height: 40px;
  }

  .el-form-item {
    margin-bottom: 12px;

    &.el-form-item--small {
      .el-form-item__content {
        line-height: 32px;
      }
    }
  }
}
.preview_wrap{
  margin-left: 20px;
  margin-top: 20px;
  width: 750px;
  height: 594px;
  background: #fff url() no-repeat center;
  background-size: cover;
  transform: scale(0.28);
  transform-origin: top left;
  box-shadow: 0 2px 6px 0 rgb(209 209 209 / 50%);
  .change_wrap {
    width: 100%;
    height: 143px;
    background: #ffd9d9;
    position: relative;
    top: 200px;
    padding: 0 15px 0 30px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .logo {
      position: relative;
      width: 80px;
      height: 80px;
      text-align: center;
      .logo_before, .logo_f8a3 .logo_after{
        position: absolute;
        top: 0;
        left: 0;
        width: 80px;
        height: 80px;
      }
      .logo_before{
        transform: rotate(30deg);
      }
      .logo_after{
        transform: rotate(60deg);
      }
      .text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 24px;
        line-height: 28px;
        z-index: 2;
      }
    }
    .discount_info {
      margin-left: 40px;
      display: flex;
      flex-direction: column;
      .times{
        display: flex;
        flex-direction: row;
        align-items: center;
        .time_text {
          padding: 0 10px;
          font-size: 28px;
          font-family: Lato, Lato-Medium;
        }
        .time {
          padding: 0 4px;
          min-width: 64px;
          height: 50px;
          line-height: 50px;
          text-align: center;
          background: #fff3cb;
          font-size: 28px;
          font-family: Lato, Lato-Medium;
          font-weight: 500;
          color: #000000;
          border-radius: 8px;
        }
        .ms{
          font-size: 36px;
        }
      }
    }
  }
}
</style>
